const Material = require('../models/materialModel');

/**
 * Material Controller
 */
const materialController = {
    async getAll(req, res) {
        try {
            const data = await Material.getAll();
            res.json({ code: 200, data });
        } catch (error) {
            res.status(500).json({ code: 500, message: error.message });
        }
    },

    async getById(req, res) {
        try {
            const { id } = req.params;
            const material = await Material.getById(id);
            if (!material) return res.status(404).json({ code: 404, message: '材料不存在' });
            res.json({ code: 200, data: material });
        } catch (error) {
            res.status(500).json({ code: 500, message: error.message });
        }
    },

    async create(req, res) {
        try {
            const insertId = await Material.create(req.body);
            res.json({ code: 200, message: '创建成功', id: insertId });
        } catch (error) {
            res.status(500).json({ code: 500, message: error.message });
        }
    },

    async update(req, res) {
        try {
            const { id } = req.params;
            const affected = await Material.update(id, req.body);
            if (!affected) return res.status(404).json({ code: 404, message: '材料不存在或更新失败' });
            res.json({ code: 200, message: '更新成功' });
        } catch (error) {
            res.status(500).json({ code: 500, message: error.message });
        }
    },

    async delete(req, res) {
        try {
            const { id } = req.params;
            const affected = await Material.delete(id);
            if (!affected) return res.status(404).json({ code: 404, message: '材料不存在或删除失败' });
            res.json({ code: 200, message: '删除成功' });
        } catch (error) {
            res.status(500).json({ code: 500, message: error.message });
        }
    }
};

module.exports = materialController;
